//
//  ByUIOrderShowVC.m
//  oc_knowledge
//
//  Created by mc on 17/1/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIOrderShowVC.h"
//VC
#import "ByUIOrderDetailVC.h"
#import "ByUIOrderPayVC.h"
#import "ByUIOrderEvaluateVC.h"

//Api
#import "ByApiOrder.h"

//model
#import "ByModelOrder.h"

//Cell
#import "ByCellOrder.h"

//Other
#import "ZKBombView.h"
#define ButtonColor [UIColor colorWithR:253 g:125 b:69]
@interface ByUIOrderShowVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, assign) NSInteger       page;

@property (nonatomic, strong) ZKBombView     *reasonView;
@end

@implementation ByUIOrderShowVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableView];
    
    [self.tableView.mj_header beginRefreshing];
//    [self getOrderListTest];
}
#pragma makr ----getter
- (NSMutableArray *)items {
    if (_items == nil) {
        _items = [NSMutableArray array];
    }
    return _items;
}

-(ZKBombView *)reasonView{
    if (_reasonView == nil) {
        _reasonView = [[ZKBombView alloc] init];
        _reasonView.positionMode = ZKBombPositionModeBottom;
        _reasonView.contentMode = ZKBombContentModePicker;
        _reasonView.popMode = ZKBombPopModeBottom;
        _reasonView.dataItems = @[@"我不想买了",@"信息填写错误，重新拍",@"卖家缺货",@"同城见面交易",@"其他原因"];
    }
    return _reasonView;
}
#pragma mark ----获取数据
- (void)getOrderList {
    
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.s_id = BY_USER.s_id;
    params.uid = BY_USER.uid;
    params.page_size = @"10";
    params.page_index = [NSString stringWithFormat:@"%li", _page];
    switch (self.order_state) {
        case 0:
            params.query_status = @"0";
            break;
        case 1:
            params.query_status = @"1";
            break;
        case 2:
            params.query_status = @"2";
            break;
        case 3:
            params.query_status = @"3";
            break;
        case 4:
            params.query_status = @"4";
            break;
        default:
            break;
    }
    [ByApiOrder getOrderList:params success:^(ByNetBaseResult *result) {
        
        ByModelOrder *listModel = result.data;
        NSArray *list = listModel.list;
        NSInteger count = [listModel.count integerValue];
        
        if (_page == 1) {
            [self.items removeAllObjects];
            [self.items addObjectsFromArray:list];
            [self.tableView.mj_footer resetNoMoreData];
        } else {
            [self.items addObjectsFromArray:list];
        }
        
        [self.tableView reloadData];
        if (self.items.count == count) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(ByNetBaseResult *result) {
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [ByCoreToolAlert showFailureWithText:result.msg];
        
    }];
}
//我的测试
- (void)getOrderListTest{
    //第一层model
    ByModelOrder *listModel = [[ByModelOrder alloc] init];
    listModel.count = @(4);
    
    //第二层model
    ByModelOrderListItem *itemModel1 = [[ByModelOrderListItem alloc] init];
    itemModel1.query_status = @"1";
    
    ByModelOrderListItem *itemModel2 = [[ByModelOrderListItem alloc] init];
    itemModel2.query_status = @"2";
    
    ByModelOrderListItem *itemModel3 = [[ByModelOrderListItem alloc] init];
    itemModel3.query_status = @"3";
    
    ByModelOrderListItem *itemModel4 = [[ByModelOrderListItem alloc] init];
    itemModel4.query_status = @"4";
    
    //第三层model
    ByModelOrderListItemProduct *proModel = [[ByModelOrderListItemProduct alloc] init];
    proModel.name = @"韩国压发饰洗脸发带韩版布艺简约交叉甜美发箍宽边百搭";
    proModel.price = @"280";
    proModel.ori_price = @"180";
    proModel.sku_desc = @"颜色分类:模特款平板款－驼色";
    proModel.count = @(20);
    proModel.tag = @"七天退换";
    itemModel1.items = @[proModel];
    itemModel2.items = @[proModel];
    itemModel3.items = @[proModel];
    itemModel4.items = @[proModel];

    listModel.list = @[itemModel1,itemModel2,itemModel3,itemModel4];
    
    if (self.items.count != 0) {
        [self.items removeAllObjects];
    }
    switch (self.order_state) {
        case 0:
            [self.items addObjectsFromArray:listModel.list];
            break;
        case 1:
            [self.items addObject:itemModel1];
            break;
        case 2:
            [self.items addObject:itemModel2];
            break;
        case 3:
            [self.items addObject:itemModel3];
            break;
        case 4:
            [self.items addObject:itemModel4];
            break;
        default:
            break;
    }
    [self.tableView reloadData];
    
}
#pragma mark ----创建视图
- (void)initTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 36) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = TABLE_COLOR;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    ByCoreRefreshGifFooter *t_footer = [ByCoreRefreshGifFooter footerWithRefreshingBlock:^{
        
        _page ++;
        [self getOrderList];
    }];
    ByCoreRefreshGifHeader *t_header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{

        _page = 1;
        [self getOrderList];
    }];
    self.tableView.mj_footer = t_footer;
    self.tableView.mj_header = t_header;
    
}

#pragma mark ---UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.items.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ByModelOrderListItem *orderModel = self.items[section];
    if ([orderModel.query_status integerValue]== 2 || orderModel.query_status.integerValue == 8) {
        return orderModel.items.count + 1;
    }else
        return orderModel.items.count + 2;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ByModelOrderListItem * orderModel = self.items[indexPath.section];
    NSInteger itemCount = orderModel.items.count;          //商品数量
    /**通用cell*/
    static NSString *indentier = @"orderActionCell";
    UITableViewCell *customCell = [tableView dequeueReusableCellWithIdentifier:indentier];
    if (customCell == nil) {
        customCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
        customCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    for (UIView *subviews in customCell.subviews) {
        [subviews removeFromSuperview];
    }
    
    if (indexPath.row < itemCount) {
        ByCellOrder *cell = [ByCellOrder cellWithTableView:tableView];
        ByModelOrderListItemProduct *proModel = orderModel.items[indexPath.row];
        proModel.isFromDetail = NO;
        cell.model = proModel;
        return cell;
    }
    else if(indexPath.row == itemCount){
        double totalPrice = 0;
        int totalCount = 0;
        for (ByModelOrderListItemProduct *model in orderModel.items) {
            totalPrice += [model.count doubleValue] *[model.price doubleValue];
            totalCount += [model.count integerValue];
        }
        NSString *totalStr = [NSString stringWithFormat:@"共%d件商品 合计：¥%.2f（含运费¥%.2f）",totalCount,totalPrice,[orderModel.post_price doubleValue]];
        UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, 20)];
        [customCell addSubview:cellLabel];
        cellLabel.text = totalStr;
        cellLabel.font = FONT(14);
        cellLabel.textAlignment = NSTextAlignmentRight;
        cellLabel.textColor = [UIColor blackColor];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = [UIColor colorWithWhite:0.90 alpha:1];
        [customCell addSubview:lineView];
        return customCell;
    }
    else{
        NSArray *buttonAry;
        switch (orderModel.query_status.integerValue){
            case 1:  //待付款
            {
                buttonAry = @[@"付款",@"取消订单",@"联系卖家"];
            }
                break;
            case 2:  //待付款
                break;
            case 3:  //待收货
            {
                buttonAry = @[@"确认收货",@"查看物流"];
            }
                break;
            case 4: //已收货
            {
                buttonAry = @[@"评价"];
            }
                break;
            case 7: //已完成
//            {
//                buttonAry = @[@"删除订单"];
//            }
                break;
            case 8://已关闭
//            {
//                buttonAry = @[@"删除订单"];
//            }
                break;
                
        }
        CGFloat x,y,width,height;
        y = 10;
        width = [@"删除订单" getSizeOfString:14].width + 20;
        height = 30;
        for (int i = 0; i < buttonAry.count; i ++) {
            CGFloat margin = 15;
            x = SCREEN_WIDTH - (width + margin) * (i+1) ;
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
            [button setTitle:buttonAry[i] forState:UIControlStateNormal];
            [customCell addSubview:button];
            button.layer.borderWidth = 1;
            button.layer.cornerRadius = 4.0;
            button.titleLabel.font = FONT(14);
            button.tag = indexPath.section;
            if (i == 0) {
                [button setTitleColor:ButtonColor forState:UIControlStateNormal];
                button.layer.borderColor = ButtonColor.CGColor;
            }else{
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                button.layer.borderColor = [UIColor colorWithWhite:0.95 alpha:1].CGColor;
            }
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        return customCell;

    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ByModelOrderListItem *orderModel = self.items[indexPath.section];
    NSInteger itemCount = orderModel.items.count;          //商品数量
    if (indexPath.row < itemCount) {
        return 92;
    }else if(indexPath.row == itemCount){
        return 40;
    }else
        return 50;

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    ByModelOrderListItem * orderModel = self.items[section];
    NSString *str;
    switch (orderModel.query_status.integerValue){
        case 1:  //待付款
        {
            str = @"等待买家付款";
        }
            break;
        case 2:  //代发货
        {
            str = @"等待卖家发货";
        }
            break;
        case 3:  //待收货
        {
            str = @"卖家已发货";
        }
            break;
        case 4: //待评价
        {
           str = @"交易成功";
        }
            break;
        case 7: //交易完成
        {
            str = @"交易成功";
        }
            break;
        case 8: //交易关闭
        {
            str = @"交易关闭";
        }
            break;
    }
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    contentView.backgroundColor = [UIColor whiteColor];
    
    //订单状态
    CGFloat x,y,width,height;
    width = [str getSizeOfString:14].width + 10;
    height = 20;
    x = SCREEN_WIDTH - width - 10;
    y = 10;
    UILabel *statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    statusLabel.text = str;
    statusLabel.font = FONT(14);
    statusLabel.textColor = ButtonColor;
    [contentView addSubview:statusLabel];
    
    //商铺图标
    x = 10;
    width = height = 20;
    UIImageView *store_img = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [store_img setImageWithURL:[NSURL URLWithString:orderModel.store_logo] placeholderImage:DEFAULT_IMAGE completed:nil];
    [contentView addSubview:store_img];
    
    //商铺名称
    x = store_img.right + 10;
    y = 10;
    height = 20;
    width = SCREEN_WIDTH - x - statusLabel.width - 20;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    nameLabel.text = orderModel.store_name;
    nameLabel.font = FONT(14);
    [contentView addSubview:nameLabel];
    return contentView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ByModelOrderListItem * orderModel = self.items[indexPath.section];
    NSInteger itemCount = orderModel.items.count;          //商品数量
    if (indexPath.row < itemCount) {
        ByUIOrderDetailVC *vc = [[ByUIOrderDetailVC alloc] init];
        vc.order_status = [orderModel.query_status integerValue];
        vc.order_code = orderModel.order_code;
        vc.successBlock = ^{
            [self.tableView.mj_header beginRefreshing];
        };
        [self by_normalPush:vc hasNavi:YES];
    }
}

#pragma mark --按钮点击事件
- (void)buttonAction:(UIButton *)button{
    ByModelOrderListItem * orderModel = self.items[button.tag];
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.uid = BY_USER.uid;
    model.order_code = orderModel.order_code;
    model.s_id = BY_USER.s_id;
    if ([button.titleLabel.text isEqualToString:@"联系卖家"]) {
        [ByCoreToolAlert showOnlyText:@"联系卖家"];
    }
    else if ([button.titleLabel.text isEqualToString:@"取消订单"]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否取消订单" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [ByCoreToolAlert showLoadind:@"处理中..."];
            [ByApiOrder cancleOrder:model success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.data];
                [self.tableView.mj_header beginRefreshing];
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showOnlyText:result.msg];
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:sureAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    else if ([button.titleLabel.text isEqualToString:@"付款"]){

        [ByCoreToolAlert showLoadind:@"正在验证订单..."];
        [ByApiOrder repayOrder:model success:^(ByNetBaseResult *result) {
            [ByCoreToolAlert hideHud];
            
            ByModelOrderPay *paymodel = result.data;
            ByUIOrderPayVC *vc = [[ByUIOrderPayVC alloc] init];
            vc.type = 1;
            vc.payModel = paymodel;
            vc.fee = paymodel.total_price;
            [self by_normalPush:vc hasNavi:YES];
            
            vc.successAction = ^ {
                [self.tableView.mj_header beginRefreshing];
            };
            vc.failureAction = ^ {
                [self.tableView.mj_header beginRefreshing];
            };

            
        } failure:^(ByNetBaseResult *result) {
            [ByCoreToolAlert showOnlyText:result.msg];
        }];

        
    }
    else if ([button.titleLabel.text isEqualToString:@"确认收货"]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否确认收货" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            NSInteger section = button.tag;
            ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
            params.uid = BY_USER.uid;
            params.s_id = BY_USER.s_id;
            ByModelOrderListItem *itemModel = self.items[section];
            params.order_code = itemModel.order_code;
            [ByCoreToolAlert showLoadind:@"正在确认收货..."];
            [ByApiOrder confirmOrder:params success:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showSuccessWithText:@"确认成功"];
                [self.tableView.mj_header beginRefreshing];
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showFailureWithText:result.msg];
            }];

        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:sureAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];

 
    }
    else if ([button.titleLabel.text isEqualToString:@"查看物流"]){
        [ByCoreToolAlert showOnlyText:@"查看物流"];

    }
    else if ([button.titleLabel.text isEqualToString:@"延长收货"]){
        [ByCoreToolAlert showOnlyText:@"延长收货"];

    }
    else if ([button.titleLabel.text isEqualToString:@"评价"]){
//        [ByCoreToolAlert showOnlyText:@"评价"];
        ByModelOrderDetail *detailModel = [[ByModelOrderDetail alloc] init];
        detailModel.order_code = orderModel.order_code;
        detailModel.items = [orderModel.items copy];
        detailModel.store_id = orderModel.store_id;
        ByUIOrderEvaluateVC *vc = [[ByUIOrderEvaluateVC alloc] init];
        vc.model = detailModel;
        [self by_normalPush:vc hasNavi:YES];

    }
    else if ([button.titleLabel.text isEqualToString:@"删除订单"]){
        [ByCoreToolAlert showOnlyText:@"删除订单"];

    }
    
}
@end


